/*
    包含多个由action触发去直接更新状态的方法的对象
*/
import {RECEIVE_ADDRESS, RECEIVE_FOODTYPE,
  RECEIVE_SHOPLIST, RECEIVE_USER_INFO,
  REMOVE_USER_INFO, RECEIVE_SHOPGOODS,
  RECEIVE_SHOPRATINGS, RECEIVE_SHOPINFO,
  INCREMENT_FOOD_COUNT, DECREMENT_FOOD_COUNT,
  ADD_FOOD_TO_CART, EMPTY_CART_FOODS,
  REMOVE_FOOD_TOCART, RECEIVE_SEARCH_SHOPLIST,
  RECEIVE_FOOD_IN_ORDER} from './mutations-types'

import Vue from 'vue'

export default {
// 方法名是[ADD_TASK] 而不是 ADD_TASK,如果直接写ADD_TASK则方法名就为ADD_TASK而不是常量名对应的值‘add_task’
  // 接收地址
  [RECEIVE_ADDRESS] (state, {address}) { // 所有传递来的参数必须为Object，所以用{包裹}
    state.address = address
  },

  // 接收食物列表
  [RECEIVE_FOODTYPE] (state, {foodType}) {
    state.foodType = foodType
  },

  // 接收商家列表
  [RECEIVE_SHOPLIST] (state, {shopList}) {
    state.shopList = shopList
  },

  // 接收用户信息
  [RECEIVE_USER_INFO] (state, {userInfo}) {
    state.userInfo = userInfo
  },

  // 删除用户信息(用户登出，删除用户信息同时删除订单信息)
  [REMOVE_USER_INFO] (state) {
    state.userInfo = {}
    state.order = []
  },

  // 接收商家商品
  [RECEIVE_SHOPGOODS] (state, {shopGoods}) {
    state.shopGoods = shopGoods
  },

  // 接收商家商品
  [RECEIVE_SHOPRATINGS] (state, {shopRatings}) {
    state.shopRatings = shopRatings
  },

  // 接收商家商品
  [RECEIVE_SHOPINFO] (state, {shopInfo}) {
    state.shopInfo = shopInfo
  },

  // 增加食物数量
  [INCREMENT_FOOD_COUNT] (state, {food}) {
    if (!food.count) { // 第一次增加，此前food未有count属性，属于undefined，强转!为true
      // food.count = 1 // 不会触发视图更新 (没有数据绑定)
      /*
      vue的组件都是响应式的，且都会实时触发视图更新。 (有数据绑定)
      但有一种情况不会触发视图更新：已有的响应式布局对象，新增了属性，此时该属性值改变不会触发视图更新
      vue中给定的set方法就是用来处理此类情况↓
      Vue.set(target, propertyName/index, propertyValue)
      */
      Vue.set(food, 'count', 1)
    } else { // 之后就点一次加一下即可
      food.count++
    }
  },

  // 减少食物数量
  [DECREMENT_FOOD_COUNT] (state, {food}) {
    if (food.count) { // 当数量大于0，数量才会减少
      food.count--
    }
  },

  // 添加food进购物车
  [ADD_FOOD_TO_CART] (state, {food}) {
    state.cartFoods.push(food)
  },

  // 点击-按钮时，当该food的count值<=0时,从数组中移除该食物(index为该food在数组中的下标)
  [REMOVE_FOOD_TOCART] (state, {index}) {
    state.cartFoods.splice(index, 1)
  },

  // 清空购物车, 将所有购物车内food的count清零，再把food移除出cartFoods
  [EMPTY_CART_FOODS] (state) {
    state.cartFoods.forEach(food => {
      food.count = 0
    })
    state.cartFoods = []
  },

  // 根据关键字搜索得到的商家列表
  [RECEIVE_SEARCH_SHOPLIST] (state, {shopList}) {
    state.searchShopList = shopList
  },

  // 商品结算时购物车内食物
  [RECEIVE_FOOD_IN_ORDER] (state, {foods, shopinfo}) {
    state.order[0] = foods
    state.order[1] = shopinfo
  }
}
